<?php

namespace app\cps\service;

use app\common\Common;
use app\common\Error;
use think\facade\Cache;
use app\model\TencentDataSource;
use app\model\ResponsibilityPerson;
use app\model\Applet;
use app\model\OfficialAccounts;

class TencentService
{
    private $requestUrl = 'https://api.e.qq.com/v1.2/';
    private $tencentDataSourceModel;
    private $responsibilityPersonModel;
    private $appletModel;
    private $officialAccountsModel;

    public function __construct(TencentDataSource $tencentDataSourceModel, ResponsibilityPerson $responsibilityPersonModel, Applet $appletModel, OfficialAccounts $officialAccountsModel)
    {
        $this->tencentDataSourceModel = $tencentDataSourceModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
        $this->appletModel = $appletModel;
        $this->officialAccountsModel = $officialAccountsModel;
    }

    /**
     * 根据code获取腾讯开发者accessToken
     * 
     * @author liu
     * @param code
     * @return
    */
    public function getTencentAccessTokenByCode($code)
    {
        $developerInfo = config('tencent.developer_info');

        $url = 'https://api.e.qq.com/oauth/token?client_id='.$developerInfo['client_id'].'&client_secret='.$developerInfo['client_secret'].'&grant_type=authorization_code&authorization_code='.$code.'&redirect_uri='.$developerInfo['redirect_uri'];

        $data = file_get_contents($url);

        file_put_contents('./tencent_monitoring_link.txt', date('Y-m-d H:i:s').' ：'.json_encode($data).';'.PHP_EOL, FILE_APPEND);
        $tencentData = json_decode($data, true);

        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $redis->set(config('tencent.developer_access_token'),  $tencentData['data']['access_token'],  $tencentData['data']['access_token_expires_in']);
        $redis->set(config('tencent.developer_refresh_token'), $tencentData['data']['refresh_token']);
    }

    // 腾讯数据源id列表
    public function getTencentDataSourceIdList($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $officialAccountId = $userInfo['cps_used_official_account_id'];
        $responsibilityPersonId = $userInfo['cps_user_id'];

        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');
        

        // 账户ID搜索
        if (!empty($params['account_id'])) {
            $where[] = ['account_id', '=', $params['account_id']];
        }

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id, name');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonName = array_column($responsibilityPersonData, 'name', 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id, name');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonName = array_column($responsibilityPersonData, 'name', 'id');
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
            $where[] = ['official_account_id', '=', $officialAccountId];
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            
            $where[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
            $where[] = ['official_account_id', '=', $officialAccountId];
            $responsibilityPersonName = [$userInfo['cps_user_id'] => $userInfo['cps_user_name']];
        } else {
            $responsibilityPersonName = [$userInfo['cps_user_id'] => $userInfo['cps_user_name']];
        }

        $data = $this->tencentDataSourceModel->getPagingDataByWhere($where, $page, $limit, 'responsibility_person_id, source_id, type, applet_id, name, created_at, account_id');

        if ($data['data']) {
            $appletIds = array_column($data['data'], 'applet_id');
            $appletIdArray = array_unique($appletIds);
            $appletData = $this->appletModel->getDataByWhere(['id' => $appletIdArray]);
            $appletData = array_column($appletData, 'name', 'id');

            foreach ($data['data'] as $key => $item) {

                $data['data'][$key]['applet_name'] = empty($appletData[$item['applet_id']]) ? '' : $appletData[$item['applet_id']];

                $data['data'][$key]['type'] = $item['type'] == 1 ? '微信小程序' : 'WEB';
                $data['data'][$key]['created_time'] = date('Y-m-d H:i:s', $item['created_at']);

                $data['data'][$key]['responsibility_person_name'] = empty($responsibilityPersonName[$item['responsibility_person_id']]) ? '' : $responsibilityPersonName[$item['responsibility_person_id']];
            }
        }

        return $data;
    }

    /**
     * 腾讯创建数据源id
     * 
     * @author liu
     * @param account_id 腾讯投放账户ID
     * @param type 用户行为源类型
     * @param name 
     * @return
    */
    public function createTencentDataSourceId($params, $userInfo)
    {
        $developerInfo = config('tencent.developer_info');
        $accessToken = Common::getTencentAdDeveloperAppAccessToken($developerInfo);

        // 判断账号ID是否已创建数据源ID
        $info = $this->tencentDataSourceModel->getInfoByWhere(['account_id' => $params['account_id']]);
        if (!empty($info)) {
            return ['message' => Error::THE_USER_ARLERDY_DATA_SOURCE_ID];
        }

        $action = 'user_action_sets/add';
        $url = $this->requestUrl . $action;

        $commonParameters = [
            'access_token' => $accessToken,
            'timestamp' => time(),
            'nonce' => md5(uniqid('', true))
        ];

        $type = $params['type'] == 1 ? 'WECHAT_MINI_PROGRAM' : 'WEB';
        $params['name'] = !empty($params['name']) ? $params['name'] : 'applet_user_action_set';

        $parameters = [
            'account_id' => $params['account_id'],
            'type' => $type,
            'name' => $params['name'],
            'enable_conversion_claim' => true
        ];

        if ($params['type'] == 1) {
            $officialAccountId = $userInfo['cps_used_official_account_id'];

            $params['applet_id'] = $this->officialAccountsModel->getInfoById($officialAccountId, 'applet_id')['applet_id'];

            $appletAppId = $this->appletModel->getInfoById($params['applet_id'], 'app_id')['app_id'];
            $parameters['wechat_app_id'] = $appletAppId;
        }

        $parameters = json_encode($parameters);
        $requestUrl = $url . '?' . http_build_query($commonParameters);

        $response = Common::curlRequest($requestUrl, 'POST', $parameters, ['Content-Type:application/json']);
        $result = json_decode($response, true);

        if (!empty($result['code'])) {
            return ['message' => $result['message']];
        }

        $params['source_id'] = $result['data']['user_action_set_id'];

        $params['official_account_id'] = $userInfo['cps_used_official_account_id'];
        $params['responsibility_person_id'] = $userInfo['cps_user_id'];

        $id = $this->tencentDataSourceModel->edit($params);

        if (empty($id)) {
            return ['message' => Error::FAIL_MESSAGE];
        }

        return [];
    }
}